package me.leiusual.sharing.repository

import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations.switchMap
import androidx.paging.Config
import androidx.paging.PagedList
import androidx.paging.toLiveData
import io.reactivex.Single
import me.leiusual.sharing.api.ApiSharing
import me.leiusual.sharing.api.model.UserAccount
import me.leiusual.sharing.api.model.UserAccountLog
import me.leiusual.sharing.repository.datasource.UserAccountDataSourceFactory
import me.leiusual.sharing.repository.model.Data
import javax.inject.Inject
import javax.inject.Singleton

/**
 * author: leiusual
 * create on: 2019-08-06
 * description:
 */
@Singleton
class UserAccountRepository @Inject constructor(
    private val apiSharing: ApiSharing
) {

  fun userAccountList(type: String): Single<List<UserAccount>> {
    return apiSharing.userAccountList(type)
  }

  fun userAccountDetail(id: Long): UserAccountDetailListing {
    val factory = UserAccountDataSourceFactory(apiSharing, id)
    val loadInitial = switchMap(factory.userAccountDataSource) { it.loadInitial }
    val pagedList = factory.toLiveData(Config(9, initialLoadSizeHint = 9))
    return UserAccountDetailListing(loadInitial, pagedList)
  }

  data class UserAccountDetailListing(
      val loadInitial: LiveData<Data<Unit>>,
      val pagedList: LiveData<PagedList<UserAccountLog>>
  )
}